import { getAuthPhone } from "@/service/api/sp-common/user";
import {
  geiWiFiQrcodeScan,
  getPubDomainShops,
  getWiFiDetail,
} from "@/service/api/sp-store/wifi";
import {
  BIND_PAGE_TYPE,
  EVENT_TRACK_EVENT_OF_RESULT_FOR_WIFI,
  PUB_DOMAIN_SHOP_SCOPE,
  SCOPE,
  WIFI_ERROR_CODE,
} from "@/pages/sp-store/const/wifi";

import handleEventTrack from "@/mixin/handleEventTrack";

export default {
  mixins: [handleEventTrack],
  data() {
    return {
      validateWiFiNum: 0,
    };
  },
  methods: {
    getPhoneNumber(event = null) {
      if (event) {
        this.$refs.addWifiFormRef
          .validate()
          .then(async () => {
            if (event?.detail?.errMsg) {
              if (event?.detail?.errMsg === "getPhoneNumber:ok") {
                const { encryptedData, iv } = event.detail;
                const phoneRes = await getAuthPhone({
                  encryptedData,
                  ivStr: iv,
                });
                if (phoneRes) {
                  const { phoneNumber } = phoneRes;
                  this.params.phone = phoneNumber;
                  this.$nextTick(() => {
                    //继续校验WiFi
                    this.handleValidateWiFi();
                  });
                }
              }
            }
          })
          .catch((err) => {
            // if (err[0]?.field === "wifiName") {
            //   uni.$u.toast("请输入WiFi账号");
            // }
            this.handleEventTrack({
              ...this.params,
              ...this.eventTrackMustInfo,
              status: EVENT_TRACK_EVENT_OF_RESULT_FOR_WIFI.BUSINESS_FAIL,
              failReason: "未输入完整WiFi信息" + JSON.stringify(err),
            }); //数据埋点
          });
      }
    },
    async handleGetPubDomainShops() {
      const pubDomainShops = await getPubDomainShops({
        phone: this.params.phone,
      });
      console.log("门店列表", pubDomainShops);
      //-----------检查发现存在绑定过商户---------
      //返回数据pubDomainShops，长度0是路人，长度大于1是多个门店
      if (pubDomainShops) {
        if (pubDomainShops?.length > 0) {
          this.fetchBusinessList(pubDomainShops);
        }
        //长度0是路人
        if (pubDomainShops.length === PUB_DOMAIN_SHOP_SCOPE.DEFAULT_USER) {
          //-----------也有可能没有绑定过--->继续校验WiFi-----------
          await this.handleSubmitWiFi();
        }
        //长度1是单个门店，
        if (pubDomainShops.length === PUB_DOMAIN_SHOP_SCOPE.SINGLE_DOMAIN) {
          const shop = pubDomainShops[0];
          this.bindBusinessTitle = `发现本手机号与商户【${shop.shopName}】一致，是否绑定商户？`;
          //没有多个的情况下需要直接赋值
          this.tempShopId = shop.id;
          // this.params.pubDomainShopId = shop.id;
          // this.params.pubDomainBusinessId = shop.pubDomainBusinessId;
          // this.params.storeNo = shop.storeNo;
          // this.params.pubDomainShopName = shop.shopName;
          this.$nextTick(() => {
            this.isShowBindBusiness = true;
          });
        }
        //长度大于1是多个门店
        if (pubDomainShops.length > PUB_DOMAIN_SHOP_SCOPE.SINGLE_DOMAIN) {
          // 有多个的情况下需要展示门店列表
          this.bindBusinessTitle = `发现本手机号与多个商户门店一致，请选择商户门店绑定。`;
          this.$nextTick(() => {
            this.isShowBindBusiness = true;
          });
        }
      }
    },
    async fetchWiFiDetail() {
      const res = await getWiFiDetail({ id: this.options.id });
      console.log("WiFi详情", res, this.options);
      if (res) {
        this.pageType = BIND_PAGE_TYPE.EDIT;
        this.params = {
          ...res,
        };
      }
      if (!res) {
        this.urlQuery.code = this.options.code;
        this.pageType = BIND_PAGE_TYPE.BINGING;
        this.params.wifiCode = this.options.code;
        this.$nextTick(() => {
          this.innitWifiData();
        });
      }

      await this.$store.dispatch("sp-common/base/getUserWxConfig");
    },
    fetchBusinessList(data) {
      data?.map((business) => {
        business.text = business.shopName; //商户名
        business.value = business.id; //独立的businessId
        // console.log("独立的businessId", business.id);
      });
      this.businessList = data;
    },
    handleBindBusiness() {
      if (!this.tempShopId && this.businessList.length > 0) {
        uni.$u.toast("请选择商户");
        return;
      }
      this.params.pubDomainShopId = this.tempShopId;
      if (
        this.businessList &&
        this.businessList.length > PUB_DOMAIN_SHOP_SCOPE.SINGLE_DOMAIN
      ) {
        //当是多商户的时候
        const shop = this.businessList.filter(
          (b) => b.id === this.tempShopId
        )[0];
        this.params.pubDomainShopId = shop.id;
        this.params.storeNo = shop.storeNo;
        this.params.pubDomainShopName = shop.shopName;
      }
      this.handleSubmitWiFi()
        .then(() => {
          this.isShowBindBusiness = false;
        })
        .catch(() => {
          this.isShowBindBusiness = false;
        });
    },
    handleValidateWiFi() {
      // this.validateWiFiNum += 1;
      this.isShowTestWiFiFail = false;
      this.testStateLoading.isTesting = false;
      uni.showLoading({
        title: "检测WiFi中...",
      });
      const systemInfo = uni.getSystemInfoSync();
      if (systemInfo?.wifiEnabled) {
        uni.hideLoading();
        this.testStateLoading.isTesting = true;
        this.testStateLoading.testingState = "testing";
        uni.startWifi({
          success: () => {
            this.handleEventTrack({
              ...this.params,
              ...this.eventTrackMustInfo,
              status: EVENT_TRACK_EVENT_OF_RESULT_FOR_WIFI.WECHAT_SUCCESS,
              failReason: "初始化WiFi成功，获取本机WiFi开始",
            }); //数据埋点
            uni.getConnectedWifi({
              success: (res) => {
                if (res?.wifi?.SSID !== this.params?.wifiName) {
                  this.handleEventTrack({
                    ...res,
                    ...this.params,
                    ...this.eventTrackMustInfo,
                    status: EVENT_TRACK_EVENT_OF_RESULT_FOR_WIFI.WECHAT_FAIL,
                    failReason:
                      "获取本机WiFi成功，但绑定WiFi密码和手机连接WiFi不一致，原因是：" +
                      JSON.stringify(res?.wifi),
                  }); //数据埋点
                  setTimeout(() => {
                    this.testStateLoading.isTesting = false;
                    this.isShowTestWiFiFail = true;
                  }, 500);
                  return;
                }
                if (res?.wifi?.SSID === this.params?.wifiName) {
                  this.handleEventTrack({
                    ...res,
                    ...this.params,
                    ...this.eventTrackMustInfo,
                    status: EVENT_TRACK_EVENT_OF_RESULT_FOR_WIFI.WECHAT_SUCCESS,
                    failReason: "获取本机WiFi成功，校验成功",
                  }); //数据埋点
                  // setTimeout(() => {
                  //   this.testStateLoading.testingState = "success";
                  setTimeout(() => {
                    this.testStateLoading.isTesting = false;
                    this.$nextTick(() => {
                      this.testStateLoading.testingState = "testing";
                    });
                    //检验完成以后，假如是绑定，需要弹出门店。是编辑，直接保存
                    if (this.pageType === BIND_PAGE_TYPE.BINGING) {
                      this.handleGetPubDomainShops();
                    }
                    if (this.pageType === BIND_PAGE_TYPE.EDIT) {
                      this.handleSubmitWiFi();
                    }
                  }, 500);
                  // }, 500);
                }
              },
              fail: (err) => {
                console.log("getConnectedWifi失败", err);
                this.handleEventTrack({
                  ...err,
                  ...this.params,
                  ...this.eventTrackMustInfo,
                  status: EVENT_TRACK_EVENT_OF_RESULT_FOR_WIFI.WECHAT_FAIL,
                  failReason: "获取本机WiFi失败，原因是" + JSON.stringify(err),
                }); //数据埋点
                setTimeout(() => {
                  this.testStateLoading.isTesting = false;
                  if (err?.errCode) {
                    this.$refs.errorModalRef.open(
                      err?.errCode
                        ? WIFI_ERROR_CODE[err?.errCode]
                        : "请先连接需绑定的WiFi"
                    );
                  } else {
                    uni.showToast({
                      icon: "none",
                      title: "请先连接需绑定的WiFi",
                    });
                  }
                }, 500);

                return;
              },
            });
          },
          fail: (err) => {
            this.testStateLoading.isTesting = false;
            this.handleEventTrack({
              ...err,
              ...this.params,
              ...this.eventTrackMustInfo,
              status: EVENT_TRACK_EVENT_OF_RESULT_FOR_WIFI.WECHAT_FAIL,
              failReason: "初始化WiFi失败，" + JSON.stringify(err),
            }); //数据埋点
            if (err?.errCode) {
              this.$refs.errorModalRef.open(
                err?.errCode ? WIFI_ERROR_CODE[err?.errCode] : "请打开手机WiFi"
              );
            } else {
              uni.showToast({
                icon: "none",
                title: "请打开手机WiFi",
              });
            }
          },
        });
      } else {
        uni.hideLoading();
        this.handleEventTrack({
          ...this.params,
          ...this.eventTrackMustInfo,
          status: EVENT_TRACK_EVENT_OF_RESULT_FOR_WIFI.WECHAT_FAIL,
          failReason: "初始化WiFi开始，" + "手机WiFi未打开",
        }); //数据埋点
        uni.showToast({
          icon: "error",
          title: "请打开手机WiFi",
        });
      }
    },
    handleToWiFiList() {
      uni.navigateTo({
        url: "pages/sp-store/pages/my-bind-wifi-list/index",
      });
    },
    handleCheckWiFi() {},
  },
};
